package framework.transport.server;

import framework.common.XConfig;
import framework.handler.XRequestHandler;
import framework.transport.codec.XMessageCodec;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Slf4j
public class NettyServer {

    private XRequestHandler xRequestHandler;

    private int port;
    public NettyServer(XRequestHandler xRequestHandler, Integer port) {
        this.xRequestHandler = xRequestHandler;
        this.port = port;
    }

    public void start() throws Exception {

        String host = InetAddress.getLocalHost().getHostAddress();
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        DefaultEventExecutorGroup serviceHandlerGroup = new DefaultEventExecutorGroup(Runtime.getRuntime().availableProcessors() * 2);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline()
                                    .addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS))
                                    .addLast(new LengthFieldBasedFrameDecoder(4 * 1024 * 1024, 6, 4, 0, 0))
                                    .addLast(new XMessageCodec())
                                    .addLast(serviceHandlerGroup, new XServerHandler(xRequestHandler));
                        }
                    });
            ChannelFuture f = serverBootstrap.bind(host, port).sync();
            f.addListener(future -> {
                if (future.isSuccess()) {
                    log.debug("rpc server start success on {}", port);
                } else {
                    log.debug("rpc server start fail on {}", port);
                }
            });
            f.channel().closeFuture().sync();
        } catch (Exception ex) {
            log.error("RPC服务启动失败");
            log.error("start err ", ex);
            throw ex;
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            serviceHandlerGroup.shutdownGracefully();
        }
    }


}
